import { defineStore } from "pinia";
import { ref } from "vue";
import {
  getRoleListApi,
  createRoleApi,
  updateRoleApi,
  deleteRoleApi,
  getRoleMenuByRoleIdApi,
  getAllRoleApi,
} from "@/api/role";
import { ElMessage } from "element-plus";

export const useRoleStore = defineStore(
  "role",
  () => {
    const roleList = ref([]);

    const allRole = ref([]);

    async function getRoleMenuByRoleId(roleId) {
      const res = await getRoleMenuByRoleIdApi(roleId);
      if (res.data.code == 200) {
        return res;
      } else {
        ElMessage.error({
          message: res.data.msg,
        });
        console.log("获取角色列表失败");
        return false;
      }
    }

    async function getRoleList(currentPage, pageSize) {
      const res = await getRoleListApi(currentPage, pageSize);
      if (res.data.code == 200) {
        roleList.value = res.data.data;
        return true;
      } else {
        ElMessage.error({
          message: res.data.msg,
        });
        console.log("获取角色列表失败");
        return false;
      }
    }

    async function createRole(data) {
      const res = await createRoleApi(data);
      if (res.data.code == 200) {
        //注意。这里不调用 getRoleList()，数据不会刷新，外部要重新调用getRoleList()
        return true;
      } else {
        ElMessage.error({
          message: res.data.msg,
        });
        console.log("创建角色失败");
        return false;
      }
    }

    async function updateRole(roleId, roleMenuArr) {
      const res = await updateRoleApi(roleId, roleMenuArr);
      if (res.data.code == 200) {
        //注意。这里不调用 getRoleList()，数据不会刷新，外部要重新调用getRoleList()
        return true;
      } else {
        ElMessage.error({
          message: res.data.msg,
        });
      }
    }

    async function deleteRole(id) {
      const res = await deleteRoleApi(id);
      if (res.data.code == 200) {
        //注意。这里不调用 getRoleList()，数据不会刷新，外部要重新调用getRoleList()
        return true;
      } else {
        ElMessage.error({
          message: res.data.msg,
        });
        console.log("删除角色失败");
        return false;
      }
    }

    async function getAllRole() {
      const res = await getAllRoleApi();
      if (res.data.code == 200) {
        allRole.value = res.data.data;
        return true;
      } else {
        ElMessage.error({
          message: res.data.msg,
        });
        console.log("获取角色列表失败");
        return false;
      }
    }

    return {
      roleList,
      allRole,
      getRoleMenuByRoleId,
      getRoleList,
      createRole,
      updateRole,
      deleteRole,
      getAllRole,
    };
  },
  {
    persist: {
      storage: sessionStorage,
      paths: ["roleList"],
    },
  }
);

export function uuseRoleStoreHook() {
  return useRoleStore(store);
}
